package com.xianggu.mybatis.mapper;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DynamicSqlParser {
    /**
     * 处理 <if> 标签
     * @param element
     * @return
     */
    public static String parseDynamicSql(Element element) {
        StringBuilder sql = new StringBuilder();
        NodeList children = element.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element childElement = (Element) node;
                String tagName = childElement.getTagName();
                if ("if".equals(tagName)) {
                    String condition = childElement.getAttribute("test");
                    String content = childElement.getTextContent().trim();
                    sql.append(" IF (").append(condition).append(") ").append(content);
                }
                // 处理其他动态 SQL 标签
            } else if (node.getNodeType() == Node.TEXT_NODE) {
                sql.append(node.getTextContent().trim());
            }
        }
        return sql.toString();
    }
}